/**
 * jsonwebtoken库
 * 
 * 1. 创建一个token   jwt.sign(数据,加密key,过期时间)
 * 2. 校验token       jwt.verify(token,加密key, (err, 数据)=>{})
 */

// 导入jsonwebtoken库
const jwt = require('jsonwebtoken');
const KEY = '12345rejwqke';

let token = jwt.sign({ username: 'atguigu', _id: '12sdfkjlkasj' }, KEY, { expiresIn: '7d' })

console.log(token);
token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImF0Z3VpZ3UiLCJfaWQiOiIxMnNkZmtqbGthc2oiLCJpYXQiOjE2ODMxNjE5ODgsImV4cCI6MTY4Mzc2Njc4OH0.-1Z6wauHF5WqSIvwInRmICGDHxgHKWYSEP_i_98AS78_123123'

jwt.verify(token, KEY, (err, data) => {
    if (err) {
        console.log('err: ', err);
    } else {
        console.log('data:', data);
    }
})


function createToken(data, expiresIn = '7d') {
    return jwt.sign(data, KEY, { expiresIn })
}

function verifyToken(token) {
    return new Promise((resolve, reject) => {
        jwt.verify(token, KEY, (err, data) => {
            if (err) {
                reject(err);
            } else {
                resolve(data);
            }
        })
    })
}